import { fetchList, process, printOrder, pickingOrder, editRemark } from '@/api/order'
import Pagination from '@/components/Pagination'
import { provinceAndCityData, regionData, provinceAndCityDataPlus, regionDataPlus, CodeToText, TextToCode } from 'element-china-area-data'
export default {
  name: 'Order',
  components: { Pagination },
  data() {
    return {
      area_options: regionDataPlus,
      selectedOptions: [],
      dto: null,
      options: [
        {
          value: '中通快递',
          label: '中通快递'
        }, {
          value: '加运美快递',
          label: '加运美快递'
        }, {
          value: '极兔速递',
          label: '极兔速递'
        }, {
          value: '韵达快递',
          label: '韵达快递'
        }, {
          value: '顺丰快递',
          label: '顺丰快递'
        }, {
          value: '京广速递',
          label: '京广速递'
        }, {
          value: '圆通速递',
          label: '圆通速递'
        }],
      statusOptions: [
        {
          value: '',
          label: '全部'
        }, {
          value: 'PAYING',
          label: '待支付'
        }, {
          value: 'SHIPPING',
          label: '待发货'
        }, {
          value: 'SHIPPED',
          label: '待收货'
        }, {
          value: 'DELIVERED',
          label: '已签收'
        }, {
          value: 'FINISHED',
          label: '已完成'
        }, {
          value: 'CLOSED',
          label: '已关闭'
        }
      ],

      printed_options:[
        {
          value: '',
          label: '不限'
        },
        {
          value: '1',
          label: '已打印'
        },
        {
          value: '0',
          label: '未打印'
        }
      ],

      orderbyOptions:[
        { label:'按下单时间↑',value:'created_at_asc' },
        { label:'按下单时间↓',value:'created_at' },
        { label:'按付款时间↓',value:'paid_at' },
        { label:'按收货时间↓',value:'receipted_at' },
      ],
      value: '',
      express_no: '',
      orderVisible: false,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 40,
        keyword: null,
        from_date: null,
        to_date: null,
        state: null,
        is_printed: null,
        orderby: 'paid_at',
        weight_min: null,
        weight_max: null,
        amount_min: null,
        amount_max: null,
        postal_code: null
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      datetime: null,
      multipleSelection: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleAreaChangeSearch(value){
      for(let i = 0; i < value.length; i++){
        if(value[i] == ''){
          this.listQuery.postal_code = i == 0 ? null : value[i - 1]
        }else if(i == 2){
          this.listQuery.postal_code = value[2]
        }
      }
      this.handleSearch()
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.orders
        this.total = response.total
        this.listLoading = false
      }).catch(error => {
        this.list = []
        this.total = 0
        this.listLoading = false
        Promise.reject(error)
      })
    },

    getDetail(row) {
      this.dto = row
      this.orderVisible = true
      this.express_no = ''
      let item_total_price = 0
      row.items.forEach(item => {
        item_total_price += item.subtotal
      })
      this.dto.total = item_total_price.toFixed(2)
    },

    ship() {
      if (!this.value || this.value === '') {
        this.$message({
          message: '请选择快递公司',
          type: 'error'
        })
        return
      }
      if (!this.express_no || this.express_no === '') {
        this.$message({
          message: '请输入运单号',
          type: 'error'
        })
        return
      }
      process(this.dto.id, {
        transition: 'ship',
        express: this.value,
        express_no: this.express_no
      }).then(res => {
        const index = this.list.findIndex(v => v.id === this.dto.id)
        this.list.splice(index, 1, res.order)
        this.orderVisible = false
        this.$notify({
          title: '操作成功',
          message: '',
          type: 'success',
          duration: 2000
        })
      })
    },

    cancel(id) {
      this.$confirm('取消订单将把客户已付金额原路退回，是否确认取消?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        process(id, {
          transition: 'close'
        }).then(res => {
          const index = this.list.findIndex(v => v.id === id)
          this.list.splice(index, 1, res.order)
          this.orderVisible = false
          this.$notify({
            title: '操作成功',
            message: '',
            type: 'success',
            duration: 2000
          })
        })
      })
    },

    cancel2(id) {
      this.$confirm('取消订单将把客户已付金额原路退回，并将订单内容恢复至购物车，是否确认取消?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        process(id, {
          transition: 'close',
          restore: 'true'
        }).then(res => {
          const index = this.list.findIndex(v => v.id === id)
          this.list.splice(index, 1, res.order)
          this.orderVisible = false
          this.$notify({
            title: '操作成功',
            message: '',
            type: 'success',
            duration: 2000
          })
        })
      })
    },

    handleSearch() {
      if (this.listQuery.keyword == '') {
        this.listQuery.keyword = null
      }
      if (this.listQuery.state == '') {
        this.listQuery.state = null
      }
      if (!this.datetime) {
        this.listQuery.from_date = null
        this.listQuery.to_date = null
      } else {
        this.listQuery.from_date = this.datetime[0]
        this.listQuery.to_date = this.datetime[1]
      }
      this.list = []
      this.total = 0
      this.getList()
    },

    print(id) {
      const routeData = this.$router.resolve({
        path: '/print/orders/' + id
      })
      window.open(routeData.href, '_blank')
    },

    printOnline: async function(id,picking_order_id){
      const loading = this.$loading({
        lock: true,
        text: '正在打印',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      let res = await new Promise((resolve,reject) => {
        printOrder(id,picking_order_id).then(res => {
          loading.close()
          resolve(res)
        }).catch(err => {
          loading.close()
          reject(err)
        })
      })
      return res
    },

    handleSelectionChange(val){
      this.multipleSelection = val;
    },

    printBatch: async function(){
      if(this.multipleSelection.length < 1){
        this.$message({
          message: '请选择需要打印的订单',
          type: 'warning'
        })
        return
      }else{
        for(let i = 0; i < this.multipleSelection.length; i++){
          const item = this.multipleSelection[i]
          await this.printOnline(item.id,'')
        }
        this.multipleSelection = []
        this.handleSearch()
      }
    },

    pickBatch: async function(){
      if(this.multipleSelection.length < 1){
        this.$message({
          message: '请选择需要拣货的订单',
          type: 'warning'
        })
        return
      }else{
        let list = []
        for(let i = 0; i < this.multipleSelection.length; i++){
          const item = this.multipleSelection[i]
          list.push(item.id)
        }
        const res = await pickingOrder(list)

        if(res.picking_order){
          this.$notify({
            title: '操作成功',
            message: '',
            type: 'success',
            duration: 1000
          })
          this.multipleSelection = []
          this.handleSearch()
        }else{
          this.$notify({
            title: '操作失败',
            message: '',
            type: 'error',
            duration: 1000
          })
        }
      }
    },

    pick_print: async function(){
      if(this.multipleSelection.length < 1){
        this.$message({
          message: '请选择需要拣货的订单',
          type: 'warning'
        })
        return
      }else{
        let list = []
        for(let i = 0; i < this.multipleSelection.length; i++){
          const item = this.multipleSelection[i]
          list.push(item.id)
        }
        const res = await pickingOrder(list)
        if(res.picking_order){
          for(let i = 0; i < this.multipleSelection.length; i++){
            const item = this.multipleSelection[i]
            await this.printOnline(item.id,res.picking_order.id)
          }
          this.multipleSelection = []
          this.handleSearch()
        }else{
          this.$notify({
            title: '操作失败',
            message: '',
            type: 'error',
            duration: 1000
          })
        }
      }
    },

    editRemark(id,remark) {
      console.log(id)
      this.$prompt('请输入备注', '订单备注', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: remark
      }).then(({ value }) => {
        editRemark(id,{
          remark: value
        }).then(res => {
          const index = this.list.findIndex(v => v.id === id)
          this.list.splice(index, 1, res.order)
          this.$notify({
            title: '操作成功',
            message: '',
            type: 'success',
            duration: 1000
          })
        })
      }).catch(() => {});
    },
  }
}
